<?php

namespace App\Http\Middleware;

use App\Exceptions\Frontend\ApiException;
use Closure;
use Illuminate\Validation\ValidationException;

class VerifyCaptcha
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     * @throws ValidationException
     * @throws ApiException
     */
    public function handle($request, Closure $next)
    {
        // return $next($request);
        $validator = \Validator::make($request->all(), [
            '__captcha_uuid' => 'required',
            '__captcha_code' => 'required'
        ]);
        $validator->validate();

        $payload = $request->only(['__captcha_uuid', '__captcha_code']);

        $uuid = $payload['__captcha_uuid'];
        $code = $payload['__captcha_code'];

        $key = \Cache::pull(sprintf('Captcha:%s', $uuid));

        if(!$key) {
            throw new ApiException('验证码已过期', 0);
        }

        if(!\Captcha::check_api($code, $key)) {
            throw new ApiException('验证码验证失败', 0);
        }
        return $next($request);
    }
}
